package com.wzb.mybatisplus.bitaction.electrumaction;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

public class SimpleElectrumClient {

    public static void main(String[] args) {
        System.out.println("简单Electrum客户端");

        try {
            String serverUrl = "https://electrum.emzy.de:50002";
            String address = "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa";

            // 测试连接
            testConnection(serverUrl);

            // 查询余额
            getBalance(serverUrl, address);

        } catch (Exception e) {
            System.err.println("错误: " + e.getMessage());
        }
    }

    private static void testConnection(String serverUrl) throws Exception {
        String request = String.format(
                "{\"jsonrpc\":\"2.0\",\"id\":\"%s\",\"method\":\"server.ping\",\"params\":[]}",
                UUID.randomUUID()
        );

        String response = sendPostRequest(serverUrl, request);
        System.out.println("连接测试: " + response);
    }

    private static void getBalance(String serverUrl, String address) throws Exception {
        String request = String.format(
                "{\"jsonrpc\":\"2.0\",\"id\":\"%s\",\"method\":\"blockchain.address.get_balance\",\"params\":[\"%s\"]}",
                UUID.randomUUID(), address
        );

        String response = sendPostRequest(serverUrl, request);
        System.out.println("余额查询: " + response);
    }

    private static String sendPostRequest(String urlString, String body) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = body.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), "utf-8"))) {
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            return response.toString();
        }
    }
}
